//
//  ShareUserVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/18.
//

import UIKit

class ShareUserVC: BaseVC {
    
    var curentUser = DMCCUser()
    var curentGroup = DMCCGroup()
    var isGroup = Bool()
    var isContact = Bool()
//    var indexArray : Array<Any> = []
    // 排序后分组数据
//    private var objectsArray : [[Any]]?
    // 头部标题keys
//    private var keysArray:[String]? = []
    
//    var myUser : UserInfo = UserInfo()
    
    init(curentUser: DMCCUser, curentGroup: DMCCGroup) {
        super.init(nibName: nil, bundle: nil)
        self.curentUser = curentUser
        self.curentGroup = curentGroup
        if self.curentGroup.groupId.count > 0 {
            isGroup = true
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "推荐给朋友"
        setup()
//        self.getUserInfo()
        self.getGroup()
//        self.requestData(isRefresh: false)
    }

    @IBAction func back(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    @IBAction func done(_ sender: Any) {
        
        
        var userArray = [DMCCUser]()
        var groupArray = [DMCCGroup]()
        for user in dataSource{
            if user is DMCCUser {
                let info = user as! DMCCUser
                if info.uiData as! String == "1" {
                    userArray.append(info)
                }
                
            } else{
                let info = user as! DMCCGroup
                if info.uiData as! String == "1" {
                    groupArray.append(info)
                }
            }
            
        }
        
        if isContact {
            updateCon(osngId: curentUser.userId)
            updateCon(osngId: curentGroup.groupId)
            Task {
                for user in userArray{
                    if isGroup {
                        let (msg,error) = await gosnMessage.sendCardMessage(user.userId, curentGroup.groupId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }else{
                        let (msg,error) = await gosnMessage.sendCardMessage(user.userId, curentUser.userId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }
                }
                
                for groupInfo in groupArray {
                    
                    if isGroup {
                        let (msg,error) = await gosnMessage.sendCardMessage(groupInfo.groupId, curentGroup.groupId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }else{
                        let (msg,error) = await gosnMessage.sendCardMessage(groupInfo.groupId, curentUser.userId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }
                }
            }
        }else{
            Task {
                for user in userArray{
                    updateCon(osngId: user.userId)
                    if isGroup {
                        let (msg,error) = await gosnMessage.sendCardMessage(curentGroup.groupId, user.userId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }else{
                        let (msg,error) = await gosnMessage.sendCardMessage(curentUser.userId, user.userId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }
                }
                
                for groupInfo in groupArray {
                    updateCon(osngId: groupInfo.groupId)
                    if isGroup {
                        
                        let (msg,error) = await gosnMessage.sendCardMessage(curentGroup.groupId, groupInfo.groupId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }else{
                        let (msg,error) = await gosnMessage.sendCardMessage(curentUser.userId, groupInfo.groupId)
                        await MainActor.run {
                            if error == nil {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                            }
                        }

                    }
                }
            }
        }
        

        

//        if isSend == false {
//            self.dismiss(animated: true)
//        }else {
            MHAlert.showMessage("发送成功")
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
            self.dismiss(animated: true)
        }))

    }
    
    func updateCon (osngId:String) {
        if (gosnConversation.getConversationInfo(osngId) == nil) {
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                geventService.post(.kUpDateConversation, "")
            }
        }
    }
    
    func getGroup() {
        var newGroups = [String]()
//        let cons = gosnConversation.getConversationInfoWithLine([1], line: 1)!
        let cons = gosnConversation.getConversationList(OsnConversationType.Group)
        for conv in cons {
            newGroups.append(conv.targetId)
        }
        
        let ids = gosnGroup.listGroupInfo(isFav: true)
        for str in ids {
            newGroups.append(str.groupId)
        }
//        var tempArray = NSMutableArray(array: ids!) as! [String]
        
        
        let sets = NSSet(array: newGroups as [Any])
        let groups = Array(sets)
        
//        counts = dataSource.count
        if groups.isEmpty {
            getListData()
            return
        }
        
        
//        var equal = 0
        for groupId in groups {
            if groupId as! String == curentGroup.groupId {
                continue
            }
            let groupInfo = gosnGroup.getGroupInfoDefault(groupId as! String)
            dataSource.append(groupInfo)
        }
        self.getListData()
    }

    @objc func getListData() {
//        dataSource.removeAll()
        self.requestData()
        _ = gosnFriend.getFriendList()
        //DMCCIMService.getInstance().getFriendList(true)
//        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
//            self.tableView.mj_header?.endRefreshing()
//        }))
    }
    
    func requestData () {
        let friendArr = gosnFriend.getFriendList()
        var count = friendArr.count
        for f in friendArr {
            if f.userId == curentUser.userId {
                count -= 1
                continue
            }
            self.getUser(friendID: f.friendId, count: count )
        }
    }
    
    func getUser (friendID:String,count:Int) {
        let user = gosnUser.getUserInfoDefault(friendID)
        dataSource.append(user)
        if dataSource.count == count {
            GK_main_async_safe {
                self.tableView.reloadData()
            }
        }
    }

    

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    

    
    //MARK: 设置表头的高度。如果使用自定义表头，该方法必须要实现，否则自定义表头无法执行，也不会报错
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
        let user = dataSource[indexPath.row]
        
        
        
        if user is DMCCUser {
            let info = user as! DMCCUser
            if info.uiData as! String == "1" {
                cell.selectImg.isHidden = false
            }else{
                cell.selectImg.isHidden = true
            }
            cell.setUserInfo(userInfo: info)
        }else if user is DMCCGroup {
            let info = user as! DMCCGroup
            if info.uiData as! String == "1" {
                cell.selectImg.isHidden = false
            }else{
                cell.selectImg.isHidden = true
            }
            cell.setGroup(group: info)
//            cell.setGroup(group: user as! GroupInfo)
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        let user = dataSource[indexPath.row]
        if user is DMCCUser {
            let info = user as! DMCCUser
            info.uiData = info.uiData as! String == "1" ? "" : "1"
        }else if user is DMCCGroup {
            let info = user as! DMCCGroup
            info.uiData = info.uiData as! String == "1" ? "" : "1"
        }
        self.tableView.reloadData()
    }
    
    
//    func sendMessage(content: OsnMessageContent, userInfo: UserInfo) {
//        let conv = ConversationInfo.init(param: curentUser.userId, type: 0)
//        DMCCIMService.getInstance().send(conv, content: content, pwd: nil) { hash, timestamp in
//            // Success handler
//        } error: { errorCode in
//            // Error handler
//            MHAlert.showError("分享失败")
//        } sendingCB: { str, err in
//            
//        }
//    }
//
//    func sendMessage(content: MessageInfoContent, groupInfo: GroupInfo) {
//        let conv = ConversationInfo.init(param: curentGroup.groupId, type: 1)
//        DMCCIMService.getInstance().send(conv, content: content, pwd: nil) { hash, timestamp in
//            // Success handler
//        } error: { errorCode in
//            // Error handler
//            MHAlert.showError("分享失败")
//        } sendingCB: { str, err in
//            
//        }
//    }
//    
    func setup () {

        tableStytle = .plain
        tableView.frame = CGRect(x: 0, y: GKNavHeight + 10, width: kScreenWidth, height: kScreenHeight - GKNavHeight - 10)
//        let head = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(getListData))
//        head.lastUpdatedTimeLabel?.isHidden = true
//        head.stateLabel?.isHidden = true
//        self.tableView.mj_header = head
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 76, bottom: 0, right: 0)
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
    }
}
